package com.mjf.net.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPSendB {
    public static void main(String[] args) throws IOException {

        // 创建 DatagramSocket 对象，准备在 9998端口 接收数据
        DatagramSocket socket = new DatagramSocket(9998);

        // 将需要发送的数据，封装到 DatagramPacket 对象
        byte[] data = "hello 明天吃火锅~".getBytes();

        DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("192.168.124.9"), 9999);

        socket.send(packet);


        // 接收从A端回复的信息
        // 构建一个 DatagramPacket 对象，准备接收数据
        byte[] buf = new byte[1024];
        packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);

        // 把 packet 进行拆包，取出数据，并显示
        int length = packet.getLength();
        data = packet.getData();
        String s = new String(data, 0, length);
        System.out.println(s);

        socket.close();

    }
}
